package com.example.secondhandspringboot.service.impl;

import com.example.secondhandspringboot.constant.RedisConstant;
import com.example.secondhandspringboot.service.HotSearchService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class HotSearchServiceImpl implements HotSearchService {

    private final StringRedisTemplate stringRedisTemplate;

    //处理搜索词
    @Override
    public void sortHotSearch(String search) {
        //去除无用空格
        String replaceSearch = search.replace(" ","");
        ZSetOperations<String, String> forZSet = stringRedisTemplate.opsForZSet();
        Double score = forZSet.score(RedisConstant.HOT_SEARCH, replaceSearch);
        //不存在则创建
        if (score == null){
            if (forZSet.size(RedisConstant.HOT_SEARCH) > 9){
                forZSet.removeRange(RedisConstant.HOT_SEARCH,0,0);
            }
            forZSet.add(RedisConstant.HOT_SEARCH, replaceSearch,1);
        }else {
            forZSet.incrementScore(RedisConstant.HOT_SEARCH, replaceSearch,1);
        }
    }
}
